package org.itstack.demo.netty.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

import java.util.Date;

public class MyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        System.out.println("链接报告开始");
        System.out.println("链接报告信息：本客户端连接到服务端。ChannelId：" + socketChannel.id());
        System.out.println("链接报告IP：" + socketChannel.localAddress().getHostString());
        System.out.println("链接报告Port：" + socketChannel.localAddress().getPort());
        System.out.println("链接报告完毕！");

        String str = "通知客户端连接建立成功" + new Date() + " " + socketChannel.localAddress().getHostString() + "\r\n";
        ctx.writeAndFlush(str);

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("断开链接！" + ctx.channel().localAddress().toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("接收到消息：" + msg);
        String str = "客户端收到：" + new Date() + " " + new Date() + msg + "\r\n";
        ctx.writeAndFlush(str);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常信息：" + cause.getMessage());
    }
}
